package com.zym.framework.area;

import com.zym.framework.model.SelectModel;
import javafx.event.EventHandler;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Skin;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseEvent;

import java.util.HashMap;
import java.util.Map;

/**
 * QQ 165149324
 * 臧英明
 *
 * @author
 * @create 2021-03-02
 */
public class Area  extends ComboBox<String> {
    private AreaComboBoxTableView areaComboBoxTableView;
    private Map<String,String> map = new HashMap<>();

    public Area(){
        setPromptText("请选择您的区域");
        setEditable(true);
        this.areaComboBoxTableView = new AreaComboBoxTableView(this);
        TreeView table = this.areaComboBoxTableView.getTable();
        areaComboBoxTableView.setOnMouseClickedsetOnMouseClicked(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                if(mouseEvent.getClickCount() == 2){
                    TreeItem<SelectModel> item = (TreeItem<SelectModel>) table.getSelectionModel().getSelectedItem();
                    SelectModel value = item.getValue();
                    if(value.getId().equals("ROOT")){
                        setValue(null);
                        item.setExpanded(true);
                        return;
                    }
                    int level = value.getLevel();
                    if(map.size() > 0){
                        for (int i = level+1; i <=map.size() ; i++) {
                            map.remove(String.valueOf(i));
                        }
                    }

                    areaComboBoxTableView.getLeftTree(item);
                    //层级计算器
                    map.put(String.valueOf(value.getLevel()),value.getValue());
                    setValue(getMap());
                }

            }
        });
    }
    public void setTableWidth(double value){
        areaComboBoxTableView.setTableWidth(value);
    }
    private String getMap() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i <map.size() ; i++) {
            String s = map.get(String.valueOf(i));
            sb.append(s).append("/");
        }
        sb.deleteCharAt(sb.lastIndexOf("/"));
        return sb.toString();
    }
    @Override protected Skin<?> createDefaultSkin() {
        return areaComboBoxTableView;
    }
}
